package cn.lijiajia3515.cairo.auth.config.security;

import cn.lijiajia3515.cairo.auth.framework.AccountRepository;
import cn.lijiajia3515.cairo.auth.framework.security.oauth2.client.userinfo.CairoOAuth2UserService;
import cn.lijiajia3515.cairo.auth.framework.security.rememberme.RedisPersistentTokenRepository;
import cn.lijiajia3515.cairo.auth.framework.security.user.CairoUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration(proxyBeanMethods = false)
public class LoginSecurityBeanConfig {
	// -------------- 登录 配置 --------------

	/**
	 * 密码加密策略
	 *
	 * @return 密码加密策略
	 */
	@Bean
	PasswordEncoder cairoPasswordEncoder() {
		return PasswordEncoderFactories.createDelegatingPasswordEncoder();
	}

	/**
	 * account cache
	 *
	 * @param mongoTemplate mongo
	 * @return 仓库
	 */
	@Bean
	AccountRepository accountRepository(MongoTemplate mongoTemplate) {
		return new AccountRepository(mongoTemplate);
	}

	/**
	 * form login
	 *
	 * @param mongoTemplate mongo
	 * @param repository    account仓库
	 * @return service
	 */
	@Bean
	@Primary
	CairoUserService cairoUserServices(MongoTemplate mongoTemplate, AccountRepository repository) {
		return new CairoUserService(mongoTemplate, repository);
	}

	/**
	 * oauth2 登录 服务
	 *
	 * @param mongoTemplate     mongo
	 * @param accountRepository account 仓库
	 * @return service
	 */
	@Bean
	CairoOAuth2UserService cairoOAuth2UserService(MongoTemplate mongoTemplate, AccountRepository accountRepository) {
		return new CairoOAuth2UserService(mongoTemplate, accountRepository);
	}

	/**
	 * 记住我 持久化
	 *
	 * @param namespace     命名空间
	 * @param redisTemplate redis
	 * @return persistent token repository
	 */
	@Bean
	RedisPersistentTokenRepository redisPersistentTokenRepository(@Value("${spring.application.name}") String namespace, RedisTemplate<String, Object> redisTemplate) {
		RedisPersistentTokenRepository repository = new RedisPersistentTokenRepository(redisTemplate);
		repository.setNamespace(namespace);
		return repository;
	}
}
